package md.lanjing.com.module_deal_center.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.lxh.baselibray.dialog.AlertDialog;
import com.lxh.baselibray.mvp.MvpActivity;
import com.lxh.baselibray.util.BitmapUtils;
import com.lxh.baselibray.util.CameraUtils;
import com.lxh.baselibray.util.ObjectUtils;
import com.lxh.baselibray.util.SizeUtils;
import com.lxh.baselibray.util.ToastUtils;
import com.lxh.baselibray.view.PswText;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import md.lanjing.com.module_deal_center.R;
import md.lanjing.com.module_deal_center.R2;
import md.lanjing.com.module_deal_center.bean.DealVoucherResponce;
import com.lxh.baselibray.constant.Constant;
import md.lanjing.com.module_deal_center.contact.DealVoucherContact;
import retrofit2.Response;


/**
 * 交易凭证
 */
public class DealVoucherActivity extends MvpActivity<DealVoucherContact.DealVoucherPresent> implements DealVoucherContact.IDealVoucherView {
    public static final String TRANSFER_ID = "transferId";
    public static final String PAYMENT  ="payment";
    @BindView(R2.id.iv_take_pic)
    ImageView ivTakePic;
    @BindView(R2.id.tv_up_deal_voucher)
    TextView tvUpDealVoucher;

    String transferId;

    private File outputImagepath;//存储拍完照后的图片
    private String base64Img;
    private Bitmap orc_bitmap;
    private String payment;
    public static final int TAKE_PHOTO = 1;//启动相机标识
    public static final int SELECT_PHOTO = 2;//启动相册标识
    @Override
    public void initData(Bundle savedInstanceState) {
        transferId = getIntent().getStringExtra(TRANSFER_ID);
        payment=getIntent().getStringExtra(PAYMENT);

        SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                "yyyy_MM_dd_HH_mm_ss");
        String filename = timeStampFormat.format(new Date());
        outputImagepath = new File(Environment.getExternalStorageDirectory(),
                filename + ".jpg");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_deal_voucher;
    }

    @OnClick({R2.id.tv_up_deal_voucher, R2.id.btn_confirm,R2.id.iv_take_pic})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.tv_up_deal_voucher || i == R.id.iv_take_pic) {
            showTakePhotoDialog();

        } else if (i == R.id.btn_confirm) {
            if (ObjectUtils.isEmpty(base64Img)) {
                ToastUtils.showLongToast(context, "请上传交易凭证");
                return;
            }
            showDealDialog();

        }
    }

    AlertDialog dealDialog = null;

    private void showDealDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .addDefaultAnimation()
                .setCancelable(true)
                .setContentView(R.layout.dialog_deal_pwd)
                .setWidthAndHeight(SizeUtils.dp2px(context, 279), SizeUtils.dp2px(context, 157))
                .setOnClickListener(R.id.tv_sure, v -> {
                    PswText psw = dealDialog.getView(R.id.pt_deal_pwd);
                    String dealPwd=psw.getPsw();
                    mPresent.confirmDealVoucher(context,transferId,base64Img,payment,dealPwd);
                    dealDialog.dismiss();
                    showLoadingDialog();
                }).setOnClickListener(R.id.tv_cancle, v -> dealDialog.dismiss());
        dealDialog = builder.create();
        dealDialog.show();
    }

    @Override
    public void getDealVoucherData(Response<DealVoucherResponce> response) {
        dismissLoadingDialog();
        if (response.body().getCode() == Constant.SUCCESS_CODE) {
            ToastUtils.showLongToast(context, "上传凭证成功");
        } else {
            ToastUtils.showLongToast(context, response.body().getMsg());
        }
    }

    @Override
    protected DealVoucherContact.DealVoucherPresent createPresent() {
        return new DealVoucherContact.DealVoucherPresent();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //打开相机后返回
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    tvUpDealVoucher.setVisibility(View.GONE);
                    displayImage(outputImagepath.getAbsolutePath(), ivTakePic);
                }
                break;
            //打开相册后返回
            case SELECT_PHOTO:
                if (resultCode == RESULT_OK) {
                    String imagePath = null;
                    //判断手机系统版本号
                    if (Build.VERSION.SDK_INT > 19) {
                        //4.4及以上系统使用这个方法处理图片
                        imagePath = CameraUtils.getImgeOnKitKatPath(data, context);
                    } else {
                        imagePath = CameraUtils.getImageBeforeKitKatPath(data, context);
                    }
                    tvUpDealVoucher.setVisibility(View.GONE);
                    displayImage(imagePath, ivTakePic);

                }
                break;
            default:
                break;
        }
    }

    /**
     * 拍完照和从相册获取玩图片都要执行的方法(根据图片路径显示图片)
     */
    private void displayImage(String imagePath, ImageView iv) {
        if (!TextUtils.isEmpty(imagePath)) {
            //orc_bitmap = BitmapFactory.decodeFile(imagePath);//获取图片
            orc_bitmap = CameraUtils.comp(BitmapFactory.decodeFile(imagePath)); //压缩图片
            base64Img = BitmapUtils.bitmapToBase64(orc_bitmap);
            CameraUtils.ImgUpdateDirection(imagePath, orc_bitmap, iv);//显示图片,并且判断图片显示的方向,如果不正就放正
        } else {
            ToastUtils.showLongToast(context, "图片获取失败");
        }
    }

    AlertDialog dialog = null;

    private void showTakePhotoDialog() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                                .addDefaultAnimation()
                                .setContentView(R.layout.dialog_take_photo)
                                .setWidthAndHeight(SizeUtils.dp2px(context, 228), SizeUtils.dp2px(context, 90))
                                .setCancelable(true)
                                .setOnClickListener(R.id.tv_take_photo, v -> {
                                    dialog.dismiss();
                                    Intent takePhotoIntent = CameraUtils.getTakePhotoIntent(context, outputImagepath);
                                    startActivityForResult(takePhotoIntent, TAKE_PHOTO); // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
                                }).setOnClickListener(R.id.tv_select_pic, v -> {
                                    dialog.dismiss();
                                    Intent selectPhotoIntent = CameraUtils.getSelectPhotoIntent();
                                    startActivityForResult(selectPhotoIntent, SELECT_PHOTO);
                                });
                        dialog = builder.create();
                        dialog.show();
                    } else {
                        ToastUtils.showLongToast(context, "权限未开启");
                    }
                });

    }


}
